package com.itheima.stock.service.impl;

import com.google.common.base.Strings;
import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.pojo.SysUser;
import com.itheima.stock.service.UserService;
import com.itheima.stock.vo.req.LoginReqVo;
import com.itheima.stock.vo.resp.LoginRespVo;
import com.itheima.stock.vo.resp.R;
import com.itheima.stock.vo.resp.ResponseCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    //todo: 登录代码
    @Override
    public R<LoginRespVo> login(LoginReqVo vo) {
        //判断前端输入的对象,用户名,密码是否为空
        if (vo==null || Strings.isNullOrEmpty(vo.getUsername()) ||
        Strings.isNullOrEmpty(vo.getPassword())){
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
       //根据用户名查询用户信息
        SysUser user = sysUserMapper.findByUserName(vo.getUsername());
        //判断用户是否存在,存在则密码校验比对
        if(user==null || !passwordEncoder.matches(vo.getPassword(),user.getPassword())){
            return R.error(ResponseCode.SYSTEM_PASSWORD_ERROR.getMessage());
        }
        //组装登陆成功数据
        LoginRespVo respVo = new LoginRespVo();
        //属性拷贝(user对象中的属性拷贝到respVo属性中)字段名称类型必须相同
        BeanUtils.copyProperties(user,respVo);
        return R.ok(respVo);
    }
}
